const app = getApp();
const util = require('../../../utils/util.js');
const lbbService = require('../../../pages/service/service.js');
const lbbTaskService = require('../service/task-service.js');
Page({

    /**
     * 页面的初始数据
     */
    data: {
        dataValues: {
            minOutpatientNum:null,
            maxOutpatientNum:null,
        },
        userList: [],
        companyTypeList:[],
        sourceList: [],
        projectList: [],
        showContacts: false,
        contactObj: {},
        contactTypeList: [],
        timeMarketList: [
            {
                text:'>=1个月',
                value:1
            },
            {
                text:'>=12个月',
                value:12
            },
            {
                text:'>=24个月',
                value:24
            }
        ],
        hospitalList:[
            {
                hospitalName:'1',
                hospitalId:1
            }
        ],
        loading:false,
        finished:false,
        onBeforeClose(action, done) {
            if (action == 'confirm') {
                return false
            } else {
                return true
            }
        },
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {
        let that = this
        that.getProjectList('hospital_level')
        // that.getProjectList('contact_information')
        // that.getProjectList('taskProject')
        that.getAllCategoryAndSubList('B25')
        that.getCitys()
    },
    
    //事件处理函数
    myEventListener: function (e) {
        let that = this
        console.log("myEventListener>>", e)
        if(e.detail[0]!=0){
            that.data.dataValues['provinceId']=e.detail[0]
        } 
        if(e.detail[1]!=0){
            that.data.dataValues['cityId']=e.detail[1]
        }
        if(e.detail[2]!=0){
            that.data.dataValues['districtId']=e.detail[2]
        }
        if(e.detail[3]!=0){
            that.data.dataValues['hosLevel']=e.detail[3]
        }
        that.setData({
            selectorArray: e.detail,
            dataValues:that.data.dataValues
        })
    },
    searchEventListener: function (e) {
        let that = this
        console.log('searchEventListener>>', e)
        var inputName = '';
        if (e) {
          inputName = e.detail;
          that.setData({
            inputName: inputName
          })
        } else {
          inputName = that.data.inputName;
        }
        console.log('inputName', inputName)
        if (inputName) {
          lbbService.getHospitalByKey({
            key: inputName
          }, function (res) {
            that.data.pageNum = 1;
    
            // --- 测试代码，上线需删除，桑晟量 start ---
            res.forEach(item => {
              item.unFinishTask = 8
            })
            // --- 测试代码，上线需删除，桑晟量 end ---
    
            if (res.length > 20) {
              that.setData({
                hospitalListSolid: res,
                hospitalList: res.slice(0, 20)
              })
            } else {
              that.setData({
                hospitalList: res,
                hospitalListSolid: '',
              })
            }
          })
        }
    },
    getHospitalList: function () {
        let that = this
        let selectorArray = that.data.selectorArray
        lbbService.getHospitalList({
          array: selectorArray
        }, function (res) {
          that.data.pageNum = 1;
          let accountPhone = wx.getStorageSync('accountPhone')
          if (accountPhone == '12345678901') {
            that.setData({
              hospitalList: [{
                chairAmount: 7,
                hospitalName: "苏州吴中人民医院",
                id: 14,
                pileAmount: 10,
                stretcherAmount: 0,
                versionIsNew: "new",
                versions: "H2.1-S2.8.190926"
              }],
              hospitalListSolid: '',
            })
            return
          }
          if (res.length > 20) {
            that.setData({
              hospitalListSolid: res,
              hospitalList: res.slice(0, 20)
            })
          } else {
            that.setData({
              hospitalList: res,
              hospitalListSolid: '',
            })
          }
        })
    },
    getCitys: function () {
        let that = this;
        lbbTaskService.getAreaList({}, function (res) {
          that.setData({
            propArray: res.data,
          })
        })
    },
    //获取数据字典
    getProjectList(code) {
        let that = this
        lbbTaskService.getDictByCode({
            code: code
        }, function (res) {
            if (code == 'source_channel') {
                res.data.unshift({
                    text: '请选择',
                    value: ''
                })
                that.setData({
                    sourceList: res.data,
                })
            }else if (code == 'contact_information') {
                that.setData({
                    contactTypeList: res.data
                })
            }else if(code == 'taskProject'){
                that.setData({
                    projectList: res.data
                })
            }else if(code == 'hospital_level'){
                that.setData({
                    userList:res.data
                })
            }
        })
    },
    inputStartCode(e) {
        let input = e.detail.value
        let regex = /^\d+$/;
        if (!regex.test(input)) {
            this.data.dataValues.minOutpatientNum = ''
            wx.showToast({
                title: '请输入数字',
            })
            this.setData({
                dataValues:this.data.dataValues,
                errStartColor: 'border:1px solid red;'
            })
            return
        }

        this.data.dataValues.minOutpatientNum = e.detail.value

        if (this.data.dataValues.maxOutpatientNum && this.data.dataValues.endEquCode < input) {
            this.setData({
                errStartColor: 'border:1px solid red;'
            })
            wx.showToast({
                title: '起始不可大于结束',
            })
            return
        }
        this.setData({
            dataValues:this.data.dataValues
        })
    },
    inputEndCode(e) {
        let input = e.detail.value
        let regex = /^\d+$/;
        if (!regex.test(input)) {
            this.data.dataValues.maxOutpatientNum=''
            wx.showToast({
                title: '请输入数字',
            })
            this.setData({
                dataValues:this.data.dataValues,
                errEndColor: 'border:1px solid red;'
            })
            return
        }

        this.data.dataValues.maxOutpatientNum = e.detail.value

        if (this.data.dataValues.minOutpatientNum && this.data.dataValues.minOutpatientNum > input) {
            this.setData({
                errEndColor: 'border:1px solid red;'
            })
            wx.showToast({
                title: '结束不可小于起始',
            })
            return
        }
        this.setData({
            dataValues:this.data.dataValues
        })
    },
    //根据code获取分类字典
    getAllCategoryAndSubList(code){
        let that=this
        lbbTaskService.getAllCategoryAndSubList({code},function(res){
            that.setData({
                companyTypeList:res.data
            })
        })
    },
    // 返回上一页保存数据
    handleBack(e){
        let that = this
        let pages = getCurrentPages();
        let currPage = pages[pages.length-1];
        let prevPage = pages[pages.length-2];
        lbbTaskService.getHospitalInfo({hospitalId:e.currentTarget.dataset.id},function(res){
            prevPage.data.dataValues['hospitalId'] = res.data.hospitalId
            prevPage.data.dataValues['hospitalName'] = res.data.hospitalTitle
            prevPage.data.dataValues['deviceCount'] = res.data.deviceCount
            prevPage.data.dataValues.chargeRules = res.data.chargeRules
            prevPage.setData({
                dataValues:prevPage.data.dataValues
            })
            console.log(prevPage.data.dataValues)
            wx.navigateBack({
                delta:1,
            })
        })
        
        
    },
    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady() {

    },
    //代理名称
    onChangeName(e) {
        this.data.dataValues.hosName = e.detail
        this.setData({
            dataValues: this.data.dataValues
        })
    },
    //地图获取位置
    openMap() {
        let that = this
        wx.chooseLocation({
            latitude: 31.25392392549918,
            longitude: 120.75753402740479,
            success: (res) => {
                that.data.dataValues.address = res.name
                that.data.dataValues.longitude = res.longitude
                that.data.dataValues.latitude = res.latitude
                wx.request({
                    url: 'https://api.map.baidu.com/geocoder/v2/',
                    method: 'GET',
                    data: {
                        location: res.latitude + ',' + res.longitude,
                        output: 'json',
                        coordtype: 'wgs84ll',
                        pois: 1,
                        s: 1,
                        latest_admin: 1,
                        ak: 'GQKwKHdtu8CgmxXIkXdyTkdtlfvML4Gg'
                    },
                    success(res) {
                        if (res.data.status == 0 && res.data.result.formatted_address) {
                            let address = res.data.result.formatted_address
                            that.data.dataValues.adCode = res.data.result.addressComponent.adcode
                            that.setData({
                                dataValues: that.data.dataValues
                            })
                        } else {
                            wx.showToast({
                                title: '获取位置失败,请打开手机定位重新签到',
                                icon: 'none',
                                duration: 3000
                            })
                        }
                    },
                    fail() {
                        that.setData({
                            address: null,
                        })
                    }
                })
            }
        })
    },
    //打开公司类型选择
    onBindCompanyType(){
        this.setData({
            showCompanyType:true
        })
    },
    reset() {
        let that = this
        let childObj =that.selectComponent('.my-select')
        childObj.setData({
            cityShow: '0',
            provIndex: 0,
            cityIndex: 0,
            regionIndex: 0,
            provId: 0,
            cityId: 0,
            regionId: 0,
            userName: '全部等级',
            provName: '全部省',
            cityName: '全部市',
            regionName: '全部区/县',
            prov_animationData: {}, 
            city_animationData: {}, 
            region_animationData: {},
            user_animationData: {},
        })
        that.setData({
            dataValues:{}
        })
    },
    reload() {
        let that = this
        let data = JSON.parse(JSON.stringify(that.data.dataValues))
        lbbTaskService.getHospitalList({...data},function(res){
            that.setData({
                hospitalList:res.data
            })
        })
    },
    // 切换省份
    onChangeProvId(e) {
        let that = this
        this.data.dataValues.provinceId = e.detail.id
        this.data.dataValues.cityId = ''
        this.data.dataValues.regionId = ''
        this.setData({
            dataValues:this.data.dataValues
        })
    },
    // 切换城市
    onChangeCityId(e) {
        let that = this
        this.data.dataValues.cityId = e.detail.id
        this.data.dataValues.regionId = ''
        this.setData({
            dataValues:this.data.dataValues
        })
    },
    // 切换区/县
    onChangeRegion(e) {
        let that = this
        this.data.dataValues.regionId = e.detail.id
        this.setData({
            dataValues:this.data.dataValues
        })
    },
    //代理公司类型选择回调
    onClickItem(e){
        this.data.dataValues.agentCompanyTypeText = e.detail.text
        this.data.dataValues.agentCompanyType = e.detail.id
        this.data.dataValues.agentParentCompanyType =this.data.companyTypeList[e.detail.index].id
        this.data.dataValues.mainActiveIndex = e.detail.index
        this.setData({
            showInteractPerson: false,
            dataValues: this.data.dataValues
        })
    },
    //来源渠道
    onChangeSource(e) {
        console.log(e)
        this.data.dataValues.statusTime = e.detail
        this.setData({
            dataValues: this.data.dataValues
        })
    },
    //所属项目
    onChangeCheckbox(e) {
        this.data.dataValues.projectType = e.detail
        this.setData({
            dataValues: this.data.dataValues
        })
    },
    //代理类型
    onChangeAgentType(e){
        this.data.dataValues.agentType = e.detail
        this.setData({
            dataValues: this.data.dataValues
        })
    },
    //打开新增联系人
    addContacts() {
        this.setData({
            showContacts: true
        })
    },
    //联系人姓名回调
    onChangeUserName(e) {
        this.data.contactObj.name = e.detail
        this.setData({
            contactObj: this.data.contactObj
        })
    },
    //打开联系方式列表
    onBindcontactType(e) {
        this.setData({
            contactTypeIfShow: true
        })
    },
    //选择联系方式
    okContactType(e) {
        this.data.contactObj.contactTypeText = e.detail.name
        this.data.contactObj.contactType = e.detail.id
        this.setData({
            contactTypeIfShow: false,
            contactObj: this.data.contactObj
        })
    },
    //联系号码回调
    onChangecontactWay(e) {
        this.data.contactObj.contactWay = e.detail
        this.setData({
            contactObj: this.data.contactObj
        })
    },
    //联系人职务
    onChangeposition(e) {
        this.data.contactObj.position = e.detail
        this.setData({
            contactObj: this.data.contactObj
        })
    },
    //确定添加联系人
    onConfirmContacts() {
        if (this.data.contactObj.name && this.data.contactObj.contactType && this.data.contactObj.contactWay && this.data.contactObj.position) {
            this.data.dataValues.contactList.push(this.data.contactObj)
            this.setData({
                showContacts: false,
                dataValues: this.data.dataValues,
                contactObj: {}
            })
            console.log(33, this.data.dataValues)
        } else {
            this.openPrompt()
        }
    },
    //取消添加联系人
    onCloseContacts() {
        this.setData({
            contactObj: {}
        })
    },
    //删除联系人
    delContacterBox(e){
        this.data.dataValues.contactList.splice(e.currentTarget.dataset.index,1)
        this.setData({
            dataValues:this.data.dataValues
        })
    },
    //备注
    changeRemark(e) {
        this.data.dataValues.remark = e.detail.value
        this.setData({
            dataValues: this.data.dataValues
        })
    },
    //上传图片
    setImgArr(e) {
        let that = this
        let imgArray = e.detail;
        let newUpLoadImg = []
        let oldUpLoadImg = []
        imgArray.forEach(item => {
            if (item.indexOf('http://tmp/') != -1 || item.indexOf('wxfile://tmp') != -1) {
                newUpLoadImg.push(item)
            } else {
                oldUpLoadImg.push(item)
            }
        })
        wx.showLoading({
            title: '正在上传图片',
            mask: true
        })
        util.newUpLoadImg(app.globalData.header, newUpLoadImg, 0, [], function (imgIdArray) {
            wx.hideLoading()
            oldUpLoadImg.push(...imgIdArray)
            that.data.dataValues.images = oldUpLoadImg
            that.setData({
                dataValues: that.data.dataValues
            })
        });
    },
    //提交
    btnSubmit() {
        let that = this
        let obj=JSON.parse(JSON.stringify(that.data.dataValues))
       obj.images=obj.images?obj.images.toString():''
       obj.projectType=obj.projectType?obj.projectType.toString():''
       obj.contactList=JSON.stringify(obj.contactList)
       obj.remark=obj.remark?obj.remark:''
       if(obj.agentCompanyType&&obj.contactList&&obj.name&&obj.projectType&&obj.address&&obj.adCode&&obj.sourceChannel&&(obj.agentType||obj.agentType==0)){
           lbbTaskService.addAgent({...obj},function(){
            wx.navigateBack({
                delta: 1
              })
           })
       }else{
           that.openPrompt()
       }
       console.log(111, obj)
    },
    //校验提示
    openPrompt() {
        wx.showToast({
            title: '请检查必填项',
            icon: 'error',
            duration: 2000
        })
    },
    /**
     * 生命周期函数--监听页面显示
     */
    onShow() {

    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide() {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload() {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh() {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom() {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage() {

    }
})